﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Wwtfly.CHY.BLL;
using Wwtfly.Phone.Utility.NetWork;
using System.Text;
using System.Runtime.Serialization.Json;
using Wwtfly.CHY.Model;
using System.IO;
using System.Data.Linq;
using Microsoft.Phone.Shell;
using Wwtfly.Phone.Utility;


namespace Wwtfly.CHY
{
    public partial class MainPage : PhoneApplicationPage
    {



        // 构造函数
        public MainPage()
        {
            InitializeComponent();


            Application_Init();
            }

        private void Application_Init()
        {
            //Client.CaiHongYunDomainUrl = "http://www.fiki.cc/";
            Client.CaiHongYunDomainUrl = "http://caihongyun.duapp.com/";
       

            // 打卡地址
            Client.AdressMyAttendanceShow = Client.CaiHongYunDomainUrl + "account/logon.do?do=sureAttendance";
            // 打卡地址
            Client.AdressMyAttendancePost = Client.CaiHongYunDomainUrl + "account/logon.do?do=sureAttendance";
            // / 内容显示地址
            Client.AdressVoteShowOfLogin = Client.CaiHongYunDomainUrl + "account/logon.do";
            // / 发送地址
            Client.AdressVoteSendOfLogin = Client.CaiHongYunDomainUrl + "account/logon.do?do=logon";


             //版本信息
             Version version = new System.Reflection.AssemblyName(System.Reflection.Assembly.GetExecutingAssembly().FullName).Version;
             Client.APPVersionName = version.ToString();

            ChyData.GetDataContext();

            InitUserInfo();

            ApplicationBar_Init();

        }

        private void InitUserInfo()
        {
            try
            {
                 var userInfo = (from item in ChyData.ChyDB.UserInfo
                                              orderby item.UpdateTime descending
                                                select item).FirstOrDefault();
                 if (userInfo!=null)
                 {
                     this.txtUserName.Text = userInfo.UserName;
                     this.txtPwd.Password = AESEncrypt.DecryptAES(userInfo.Pwd, Client.AesSalt, Client.AesSalt);
                 }
            }
            catch (Exception ex)
            {
                 
            }
        }

        private void ApplicationBar_Init()
        {
            ApplicationBar = new ApplicationBar();

            ApplicationBar.Mode = ApplicationBarMode.Minimized;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = true;
            ApplicationBarIconButton btnAbout = new ApplicationBarIconButton();
            btnAbout.IconUri = new Uri("/img/about/gys.png", UriKind.Relative);
            btnAbout.Text = "关于";
            btnAbout.Click += new EventHandler(btnAbout_Click);
            ApplicationBar.Buttons.Add(btnAbout);
        }

        void btnAbout_Click(object sender, EventArgs e)
        {
            string ln = "\r\n";
            String aboutStr = "版本："
                    + Client.APPVersionName + ln +
            "使用我的理由 ：" + ln +
            "1、彩虹云，你的随身工作台。" + ln +
            "2、支持广东企业彩云-考勤应用一键打卡功能。" + ln +
            "3、流量少，一次正常完整的签到过程流量仅仅才10KB。" + ln +
            "4、速度快，打卡速度在wifi情况下,不超过4秒。" + ln +
            "5、在用户名不存在或密码输入错误的情况下,免输入验证码。" + ln;
            MessageBox.Show(aboutStr,"关于彩虹云", MessageBoxButton.OK);
        }


        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if ( this.txtUserName.Text=="")
            {
                this.txtUserName.Text = "xie2@2000189738";
                this.txtPwd.Password = "adc111";
            }
          
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            int loginModel = 0;
            DisEnabledLoginBtn(loginModel, false);
            LoginCheck(loginModel, delegate()
            {
                DisEnabledLoginBtn(loginModel, true);
            });
        }



        private void btnLoginCheckIn_Click(object sender, RoutedEventArgs e)
        {
            int loginModel = 1;
            DisEnabledLoginBtn(loginModel, false);
            LoginCheck(loginModel, delegate()
            {
                DisEnabledLoginBtn(loginModel, true);
            });

        }
        private void btnLoginCheckOut_Click(object sender, RoutedEventArgs e)
        {
            int loginModel = 2;
            DisEnabledLoginBtn(loginModel, false);
            LoginCheck(loginModel, delegate()
            {
                DisEnabledLoginBtn(loginModel, true);
            });
        }

        /// <summary>
        /// 禁用或启用按钮
        /// </summary>
        /// <param name="oper">操作</param>
        private void DisEnabledLoginBtn(int oper, bool isEnabled)
        {
            this.btnLogin.IsEnabled = isEnabled;
            this.btnLoginCheckIn.IsEnabled = isEnabled;
            this.btnLoginCheckOut.IsEnabled = isEnabled;

            this.cbkRememberPwd.IsEnabled = isEnabled;
            this.cbkSaveFlow.IsEnabled = isEnabled;
        }

        private void LoginCheck(int loginMode = 0, Action callBack = null)
        {

            DateTime dtBeginDateTime = DateTime.Now;
            HttpWebClient httpWebClient = null;
            try
            {
                httpWebClient = new HttpWebClient(new Uri(Client.CaiHongYunDomainUrl));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            string userName = this.txtUserName.Text.Trim();
            string pwd = this.txtPwd.Password.Trim();
            string base64Pwd = Convert.ToBase64String(Encoding.UTF8.GetBytes(pwd));

            string postData1 = string.Format("Platform={0}&SourceType={1}&SourceTypeVersion={2}"
                , Client.Platform
                , Client.BaiduMobAd_CHANNEL
                , Client.APPVersionName);
            string postData2 = string.Format("UserName={0}&UserPwd={1}&LoginMode={2}"
                , userName
                , base64Pwd, loginMode);
            string postData = postData1 + "&" + postData2;

            httpWebClient.PostData(Client.AdressVoteSendOfLogin, postData,
                delegate(object sender1, UploadStringCompletedEventArgs eOfUc)
                {
                    string messShow = "系统繁忙，请稍后再试";
                    try
                    { 
                        OperateResult or = this.ConvertOperateResult(eOfUc.Result);
                        DateTime dtEndAttendanceDate = DateTime.Now;
                        String time = "耗时:" + (dtEndAttendanceDate - dtBeginDateTime).TotalMilliseconds / 1000.0 + "秒！";
                        //ms.obj=ms.obj+"\r\n"+time;
                        or.ResultHtml = or.ResultHtml + "\r\n" + time;

                        messShow=or.ResultHtml;
                        if (or.GetResult() || (or.IsExistsResutlCode("1,2,3,4") && loginMode == 0))
                        {
                            //记住密码操作
                            if (this.cbkRememberPwd.IsChecked.HasValue && this.cbkRememberPwd.IsChecked.Value)
                            {
                                var userInfo = (from item in ChyData.ChyDB.UserInfo
                                                where item.UserName == userName
                                                select item).FirstOrDefault();
                                userInfo = userInfo ?? new UserInfo();
                                userInfo.UserName = userName;
                                userInfo.Pwd = AESEncrypt.EncryptAES(pwd, Client.AesSalt, Client.AesSalt);
                                
                                if (userInfo.ID <= 0)
                                {
                                    userInfo.CreateTime = DateTime.Now;
                                    userInfo.UpdateTime = DateTime.Now;
                                    ChyData.ChyDB.UserInfo.InsertOnSubmit(userInfo);
                                }
                                else
                                {
                                    userInfo.UpdateTime = DateTime.Now;
                                }
                                ChyData.ChyDB.SubmitChanges();
                            }
                            else
                            {
                                var userInfo = (from item in ChyData.ChyDB.UserInfo
                                                where item.UserName == userName
                                                select item).FirstOrDefault();
                                if (userInfo != null)
                                {
                                    userInfo.UserName = userName;
                                    userInfo.Pwd = "";
                                    userInfo.UpdateTime = DateTime.Now;
                                    ChyData.ChyDB.SubmitChanges();
                                }
                            }
                        }

                        //未到打卡时间，提示-是否签 
                        if ("CheckOut_-1" == or.ResultCode)
                        {
                            if (MessageBox.Show(messShow, "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                            {
                                MyAttendanceCheckOut(httpWebClient, delegate(OperateResult checkOutResult)
                                {
                                    OperateResult orOfhCeckOutSure= this.ConvertOperateResult(checkOutResult.ResultHtml);
                                    MessageBox.Show(orOfhCeckOutSure.ResultHtml, "提示", MessageBoxButton.OK);
                                    if (callBack != null)
                                    {
                                        callBack();
                                    }
                                });
                            }
                            else {
                                if (callBack != null)
                                {
                                    callBack();
                                }
                            }
                        }
                        else
                        {
                            MessageBoxResult mbr = MessageBox.Show(messShow, "提示", MessageBoxButton.OK);
                            if (callBack != null)
                            {
                                callBack();
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "提示", MessageBoxButton.OK);
                        if (callBack != null)
                        {
                            callBack();
                        }
                    }
                });
        }


        /// <summary>
        /// json转换 OperateResult
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private OperateResult ConvertOperateResult(string str)
        {
            DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(OperateResult));
            byte[] bytesOfResult = Encoding.UTF8.GetBytes(str);
            OperateResult or = null;
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(bytesOfResult, 0, bytesOfResult.Length);
                or = (OperateResult)dcjs.ReadObject(ms);
            }
            return or;
        }

 
        /// <summary>
        /// 签退
        /// </summary>
        /// <returns></returns>
        public void MyAttendanceCheckOut(HttpWebClient httpWebClient, Action<OperateResult> checkOutCompleted)
        {
            OperateResult or = new OperateResult();
            or.ResultCode = "100";
            try
            {
                //httpWebClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(httpWebClient_DownloadStringCompleted);
                httpWebClient.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e)
                {
                    or.ResultHtml = e.Result;
                    if (checkOutCompleted != null)
                    {
                        checkOutCompleted(or);
                    }

                };
                httpWebClient.DownloadStringAsync(new Uri(Client.AdressMyAttendanceShow));
            }
            catch (Exception e)
            {
                or.ResultCode = "-99";
                or.ResultHtml = "系统异常:" + e.Message;
                if (checkOutCompleted != null)
                {
                    checkOutCompleted(or);
                }
            }
        }


    }
}

////版本信息
//Version version = new System.Reflection.AssemblyName(System.Reflection.Assembly.GetExecutingAssembly().FullName).Version;

////应用名称
//string title = ((System.Reflection.AssemblyTitleAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Reflection.AssemblyTitleAttribute), false)[0]).Title;

////应用说明
//string description = ((System.Reflection.AssemblyDescriptionAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Reflection.AssemblyDescriptionAttribute), false)[0]).Description;

////公司名称
//string company = ((System.Reflection.AssemblyCompanyAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Reflection.AssemblyCompanyAttribute), false)[0]).Company;

////产品名称
//string product = ((System.Reflection.AssemblyProductAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Reflection.AssemblyProductAttribute), false)[0]).Product;

////版权
//string copyright = ((System.Reflection.AssemblyCopyrightAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Reflection.AssemblyCopyrightAttribute), false)[0]).Copyright;